/**
 *  在线支付模块
 */
define(function(require, exports, module) {
	"require:nomunge,exports:nomunge,module:nomunge";

	$(document).on("click",".btn-group .btn",function(){
		if(!$(this).parent().hasClass("open")){$(this).parent().addClass("open");}else{$(this).parent().removeClass("open")}
		$(document).on("click",function(event){
			var _target=$(event.target).parents();
			if(!_target.hasClass("btn-group")){
				  $(".btn-group").removeClass("open");				  
			}else{_target.siblings(".btn-group").removeClass("open");}	
		});
	});/*.on("focus","a,input:button,input:submit,button,input:checkbox,input:radio",function(){this.blur()})
	.on("click",".click_span",function(){
		$(this).siblings("input:radio").click();	
	})
	.on("click",".ldh-checkbox-span",function(){
		if($(this).hasClass("checked")){
			$(this).removeClass("checked");	
			$(this).children().attr("checked",false);
		}else{$(this).addClass("checked");$(this).children().attr("checked",true);}	
	});*/
	require("../../custom/base/component-core.js");
		
	require("../../custom/base/component-md5.js");
	
	var validate = require("../../custom/base/component-validate.js");
	
	var base = require("../../custom/base/component-base.js");
	
	base.init(base);
		
	var async = require("../../custom/base/component-async.js");
	
	var head=require("../../custom/head/module-head.js");
	
	
	
		
	//初始化函数
	exports.init=function(m){
		
		window.$ldh_pay=m;
		
		base.setFromPage("common");
		
		head.init(head,true);
		
		document.title="云便利商店-支付";
		
		exports.getAccountInfo();
		
		
	};
	
	var price=$("#payAmount").text();
	
	//支付时查看我的优惠券使用优惠券支付接口,支付时查看我的账户可支付余额使用余额支付接口
	exports.getAccountInfo=function(){
		
		var params = {
			
		};
		
		eval(
					Wind.compile("async", function() {

						var data = $await(async.DDF_AsyncRequest("POST", ctx+"/shopweb/Account/getAccountInfo.do", params));
						
				
						if(data["code"]==1){
							
							if(!validate.isNull(data["balance"])){
								
								$("#ldh-yuepay").show();
								
								$("#balance").html(data["balance"]);
								
								exports.setTotalBalance(data["balance"]);
								
								//$("#balance").html("200.251");
								
								//exports.setTotalBalance("200.251");
							}
							
							if(data["coupons"].length>0){
								
								$("#ldh-redpackets").show();
								
								for(var i=0;i<data["coupons"].length;i++){
									
									if(i==0){
										
										$("#text_red_packages_balance").html(data["coupons"][i]["amount"]);
										
										this.couponId=data["coupons"][i]["couponId"];
										
										this.amount=data["coupons"][i]["amount"];
										
									}
									
									$("#couponsList").append('<li><a href=javascript:$ldh_pay.setCouponId("'+data["coupons"][i]["couponId"]+'","'+data["coupons"][i]["amount"]+'")>'+data["coupons"][i]["amount"]+'</a></li>');
									
								}
							}
								
 
						}else{
							
							alert(data["message"]);
							
						}
						
						
						
		}))().start();
		
	};
	
	//勾选余额支付
	exports.setBalancePay=function(obj){
		
		
		
		if ($(obj).hasClass("checked")) {
			$(obj).removeClass("checked");
			$(obj).children().attr("checked", false);
			$("#span_balance_pay").hide();
			$(".ldh-pay-pwd").hide();
			$("#input_pay_password").val("");
			
			exports.calculateAmount(0,"0");
			
		} else {
			
			if($("#ldh-redpackets .ldh-checkbox-span").hasClass("checked") && Number(exports.getRedAmount())>=Number(price)){
				
				alert("红包够支付了");
				return;
			}
			
			$(obj).addClass("checked");
			$(obj).children().attr("checked", true);
			$("#span_balance_pay").show();
			$(".ldh-pay-pwd").show();
			
		}	
		
		$("#input_balance").val("");
		
	};
	
	//勾选使用红包
	exports.setRedPackets=function(obj){
		
		if($("#ldh-yuepay .ldh-checkbox-span").hasClass("checked") && validate.isNull($("#input_balance").val())){
			
			return;
		}
		
		if ($(obj).hasClass("checked")) {
			$(obj).removeClass("checked");
			$(obj).children().attr("checked", false);
			$("#div_redpackage").hide();
			this.amount="";
			exports.calculateAmount(1,"");
		} else {
			
			//判断是否勾选了余额支付并且余额是否够支付,如果满足,则提示
			if(Number($("#input_balance").val())>=Number(price)){
				alert("余额已经够支付了");
				return;
			}
			this.amount=$("#text_red_packages_balance").text();
			exports.calculateAmount(1,$("#text_red_packages_balance").text());
			$(obj).addClass("checked");
			$(obj).children().attr("checked", true);
			$("#div_redpackage").show();
		}	
	};
	
	//设置总余额
	exports.setTotalBalance=function(totalBalance){
		
		this.totalBalance=totalBalance;
		
	};
	
	//获取总余额
	exports.getTotalBalance=function(){
		
		return this.totalBalance==null?"0":this.totalBalance;
		
	};
	
	
	
	//设置红包余额
	exports.setCouponId=function(couponId,amount){
		
		this.couponId=couponId;
		
		this.amount=amount;
		
		$("#text_red_packages_balance").html(amount);
		
		$(".btn-group").removeClass("open");		
		
		exports.calculateAmount(1,amount);
		
	};
	
	//获取余额ID
	exports.getCouponId=function(){
		
		return this.couponId==null?"":this.couponId;
		
	};
	
	//获取选择的红包余额
	exports.getRedAmount=function(){
		
		return this.amount==null?"0":this.amount;
		
	};
	
	

	//Firefox, Google Chrome, Opera, Safari, Internet Explorer from version 9
	var newStr="",oldStr="";
	exports.OnInput=function(event) {
		
		newStr=event.target.value;

	
		exports.OnChangeInput();
		
	};
	
	//监听input
	exports.OnChangeInput=function(){
		
		
		if(Number(newStr)>Number(price)){
			
	    	$("#input_balance").val(oldStr);
	    	
			return;
			
		}	
	
		if(!validate.isNull(newStr)){
			
			//判断第一个字符是不是.号
			if(newStr.substring(0, 1)=="."){
				
				 $("#input_balance").val(oldStr);
				 				 
				 return;
				 
			}else{
			
				//判断有没有小数点
				if(newStr.indexOf(".")>=0){
					
					var array=newStr.split(".");
					//判断字符串不能存在两个或以上的.号
					if(array.length>2){
						
						$("#input_balance").val(oldStr);
						 					
						return;
						
					}else{
						
						//当小数点后面是否为空
						if(validate.isNull(array[1])){
							
							
							//判断是否按BackSpace删除的
						/*	if(newStr.length>oldStr.length){
								$("#input_balance").val(newStr+"0");
								
							}else{
								
								$("#input_balance").val(newStr.substring(0, newStr.length-1));
							}*/
							newStr=newStr.substring(0,newStr.length-1);
							
							
						}
						
						//判断小数点后面的数是不是数字
					    if(!validate.isNull(array[1]) && !validate.isNumber(array[1]))	{
					    	
					    	$("#input_balance").val(oldStr);
					    	
					    	return;
					    }
					    
					    //小数点后面是否大于三位数字
					    if(array[1].length>3)	{
					    	
					    	$("#input_balance").val(oldStr);
					    	
					    	return;
					    }
					    
					    //判断当前输入的数字是否大于余额
					    if(Number(newStr)>Number(exports.getTotalBalance())){
					    	
					    	$("#input_balance").val(oldStr);
					    	
					    	return;
					    }else{
					    	
					    	exports.calculateAmount(0,newStr);
					    }
					   
						
						oldStr=newStr;
						
					}
					
					
				}else{
					
					//判断小数点后面的数是不是数字
				    if(!validate.isNumber(newStr))	{
				    	
				    	$("#input_balance").val(oldStr);
				    	
				    	return;
				    }
				    
				    //判断当前输入的数字是否大于余额
				    if(Number(newStr)>Number(exports.getTotalBalance())){
				    	
				    	$("#input_balance").val(oldStr);
				    	
				    	return;
				    }else{
				    	
				    	exports.calculateAmount(0,newStr);
				    	
				    	
				    }
				    
				    oldStr=newStr;
				   
					
				}
				
				
			}
			
		}else{
			
			exports.calculateAmount(0,newStr);
			
			 oldStr=newStr;
		}
		
		
		
	};
	
	// Internet Explorer
	exports.OnPropChanged=function(event) {
	    if (event.propertyName.toLowerCase () == "value") {
	    	
	        newStr=event.srcElement.value;

			exports.OnChangeInput();
	    }
	};
	
	
	exports.calculateAmount=function(type,newStr){
		
		if(type==0){

			
			var redAmount=0;
			if($("#ldh-redpackets .ldh-checkbox-span").hasClass("checked")){
				redAmount=Number(exports.getRedAmount());
			}
			
			$("#balance").text((Number(exports.getTotalBalance())-Number(newStr)).toFixed(3));
			
			if(Number(price)-Number(newStr).toFixed(2)-redAmount<0){
				
				$("#online_pay_amount").text("0");

			}else{
				
				$("#online_pay_amount").text((Number(price)-Number(newStr)-redAmount).toFixed(2));

			}
			
			
		}else{
			
			var input_balance=$("#input_balance").val();
			
			if(!validate.isNull(input_balance)){
				
				input_balance=Number(input_balance);
			}else{
				input_balance=0;
			}
			
			if(Number(price)-input_balance<=Number(exports.getRedAmount())){
				
				$("#online_pay_amount").text("0");
				
			}else{
				
				$("#online_pay_amount").text((Number(price)-input_balance-Number(exports.getRedAmount())).toFixed(2));

			}
		}
		
	
	};
	
	
	
	exports.gotoPay=function(obj){
		
		var payCheckValue=$('input:radio[name="the_payment"]:checked').val();
		
		var pay_totalMoney=$("#pay_totalMoney").val();
		
		var couponId=exports.getCouponId();
		
		var balance=$("#input_balance").val();
		
		var payPassword=$("#input_pay_password").val();
		
		if($("#ldh-yuepay .ldh-checkbox-span").hasClass("checked")){
			
			if(validate.isNull(balance)){
				
				$("#tip_pay").html("请填写余额");
				
				task("#tip_pay").start();
				
				return;
			}
		}


		if(!$("#ldh-redpackets .ldh-checkbox-span").hasClass("checked")){
			
			couponId="";
		}
		
		if(Number(exports.getRedAmount())>=Number($("#pay_totalMoney").val())){
				
			balance=0;
			
		}
		
		if(!validate.isNull(balance)){
			
			if(validate.isNull(payPassword)){
		
				$("#tip_input_pay_password").html("请填写支付密码");
				
				task("#tip_input_pay_password").start();
				
				return;
			}else{
				
				$("#tip_input_pay_password").html("");
			}
			
		}
		
		$("#gotoPayBtn").html("正在提交...");
		
		$("#gotoPayBtn").attr("disabled","disabled");
		
		$("#gotoPayBtn").css("background-color","#D3D3D3");
		
		var params = {
				"order":$("#pay_orderId").val(),
				"orderAmount":$("#online_pay_amount").text(),
				"payType":payCheckValue,
				"couponId":couponId,
				"balance":balance,
				"password":MD5(payPassword)
		};
		
		eval(
					Wind.compile("async", function() {

						var data = $await(async.DDF_AsyncRequest("POST", ctx+"/shopweb/Transaction/reconstructParams.do", params));
						
						
						if(data.code=="1"){
							
							//支付完成，不用在线支付
							if(data.payed=="1"){
								get2post(ctx+"/v1/pages/order/pay_success.jsp?orderAmount="+pay_totalMoney,"_blank");
								
							}else{
								//支付失败
								//alert(data.message);
								
								
							}
							
							//如果返回有值,表示红包或者余额支付还不够，需要在线支付
							if(!validate.isNull(data["paramValue"])){
								
								var str='';
								str+=''+data["paramValue"];
							    $("body").append(str);
							    $("#ddf_web_payForm").attr('target', '_blank');
							    $("#ddf_web_payForm").submit(); 
							}
							
							
							exports.popupShow();

						}else{
							
							$("#tip_pay").html(data.message);
							
							$("#gotoPayBtn").html("去支付");
							
							$("#gotoPayBtn").attr("disabled",false);
							
							$("#gotoPayBtn").css("background-color","#90af13");

							task("#tip_pay").start();
						}
				
						
						
						
						
		}))().start();
		
	};
	
	
	//查看订单详情
	exports.gotoOrderDetail=function(orderId){
		
		get2post(ctx+"/v1/pages/ucenter/ucenter.jsp");
		
	};
	
	
	
	//支付页面弹窗隐藏
	exports.popupHide=function(){
		$(".ldh-popup-bg").hide();	
	}
	//支付页面弹窗出现
	exports.popupShow=function(){
		$(".ldh-popup-bg").show();	
	}
	 

	//定时提示信息
	var tips_task = eval(Wind.compile("async", function (divId) {
		
	    $await(Wind.Async.sleep(2000));
	   
	    $(divId).html("");
	    
	}));
	
	var task = eval(Wind.compile("async", function (divId) {
	    $await(tips_task(divId));
	}));
	
});

